package com.woniuxy.rabbit.utils;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSON;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

import static com.woniuxy.common.constant.FinanceConstant.Exchange.ORDER_EXCHANGE;

public class MessageUtil {
    /**
     * 发消息
     * @param receivedExchang
     * @param receivedRoutingKey
     * @param msg
     */
    public static void sendMessage(String receivedExchang, String receivedRoutingKey, String msg, RabbitTemplate rabbitTemplate,StringRedisTemplate redisTemplate) {
        sendMessage(receivedExchang,receivedRoutingKey,msg,null,rabbitTemplate,redisTemplate);
    }

    public static void sendMessage(String receivedExchang, String receivedRoutingKey, String msg, String appId, RabbitTemplate rabbitTemplate, StringRedisTemplate redisTemplate) {
        CorrelationData correlationData=new CorrelationData();
        //放消息体
        Message returnedMessage=new Message(JSON.toJSONBytes(msg));
        correlationData.setReturnedMessage(returnedMessage);
        MessageProperties messageProperties = correlationData.getReturnedMessage().getMessageProperties();
        //交换机名称
        messageProperties.setReceivedExchange(receivedExchang);
        //路由键
        messageProperties.setReceivedRoutingKey(receivedRoutingKey);
        //设置appId
        messageProperties.setAppId(appId);

        //生成token，放到redis
        String token = IdUtil.fastUUID();
        redisTemplate.opsForValue().set(token,token,30, TimeUnit.SECONDS);

        //消息处理，使returnedMessage中携带appId
        MessagePostProcessor messagePostProcessor=new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setAppId(appId);
                message.getMessageProperties().setMessageId(token);
                return message;
            }
        };

        //订单
        rabbitTemplate.convertAndSend(receivedExchang,receivedRoutingKey,msg,messagePostProcessor,correlationData);
    }
}
